package com.resou.reader.activity.friendboost;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.icu.math.BigDecimal;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.resou.common.WebViewActivity;
import com.resou.reader.R;
import com.resou.reader.api.entry.FriendHelp;
import com.resou.reader.api.entry.LoginData;
import com.resou.reader.base.ToolbarActivity;
import com.resou.reader.mine.IView.UserInstance;
import com.resou.reader.reader.utils.ScreenUtils;
import com.resou.reader.utils.NetworkUtils;
import com.resou.reader.utils.eventbus.MessageEvent;
import com.resou.reader.utils.log.DLog;
import com.resou.reader.view.wave.WaveHelper;
import com.resou.reader.view.wave.WaveView;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

public class FriendBoostActivity extends ToolbarActivity<FriendBoostContract.Presenter> implements FriendBoostContract.View, UMShareListener {
    private static final String TAG = "FriendBoostActivity";
    @BindView(R.id.wave_view)
    WaveView waveView;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.tv_share)
    TextView tvShare;
    @BindView(R.id.tv_total)
    TextView tvTotal;
    @BindView(R.id.tv_available)
    TextView tvAvailable;
    @BindView(R.id.tv_storage)
    TextView tvStorage;

    private WaveHelper mWaveHelper;
    private int mDp24;
    private int mDp15;
    private FriendBoostAdapter mAdapter;

    public static void start(Context context) {
        Intent starter = new Intent(context, FriendBoostActivity.class);
//        starter.putExtra();
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_friend_boost);
        ButterKnife.bind(this);

        setTitle("15天免费活动");
        mDp24 = (int) ScreenUtils.convertDpToPixel(24, this);
        mDp15 = (int) ScreenUtils.convertDpToPixel(15, this);

        mPresenter = new FriendBoostPresenter(this);

        waveView.setBorder(10, 0xFFFFFFFF);
        waveView.setShapeType(WaveView.ShapeType.CIRCLE);
        waveView.setWaveColor(0xFFB29F57, 0xFF5A57BA);

        mAdapter = new FriendBoostAdapter();
        recyclerView.setAdapter(mAdapter);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                outRect.bottom = mDp24;
            }
        });
        initData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mWaveHelper != null) {
            mWaveHelper.cancel();
        }
        UMShareAPI.get(this).release();
    }

    @OnClick({R.id.tv_activity_rule, R.id.tv_share})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_activity_rule:
                WebViewActivity.start(this, "https://m.resouxs.com/activity/fifthrule", "活动规则");
                break;
            case R.id.tv_share:
                UMWeb web = new UMWeb("https://m.resouxs.com/activity/fifth?token=" + UserInstance.getToken());
                web.setTitle("全场免费看小说");//标题
                web.setThumb(new UMImage(this, R.mipmap.logo));  //缩略图
                web.setDescription("限时免费一时爽，邀请好友一直爽！我刚刚在热搜小说APP分享了链接，又获得了一天免费时长~你也快来参加吧！");//描述
                new ShareAction(this)
                        .setCallback(this)
                        .withMedia(web)
                        .setDisplayList(SHARE_MEDIA.QQ, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.QZONE, SHARE_MEDIA.WEIXIN_CIRCLE)
                        .open();
                break;
        }
    }

    @Override
    public void initData() {
        String token = UserInstance.getToken();
        if (TextUtils.isEmpty(token)) {
            waveView.setWaterLevelRatio(1);
            tvTotal.setText("0");
            tvAvailable.setText("0");
            tvStorage.setText("0");
            return;
        }

        if (NetworkUtils.isNetworkConnected(this)) {
            mPresenter.getUserInfo(token);
        } else {
            LoginData loginData = UserInstance.getLoginData();
            showEnergyValue(loginData);
        }

        mPresenter.loadFriendHelpList(token);
    }

    @Override
    public void showContent() {

    }

    @Override
    public void showProgress() {

    }

    @Override
    public void showError(Throwable throwable) {

    }

    @Override
    public void showEmpty() {

    }

    @Override
    public void setFriendList(List<FriendHelp> data) {
        if (data.size() > 0) {
            mAdapter.setFriends(data);
//            recyclerView.setVisibility(View.VISIBLE);
            ViewGroup.LayoutParams layoutParams = recyclerView.getLayoutParams();
            float dp225 = ScreenUtils.convertDpToPixel(225, this);
            layoutParams.height = (int) dp225;
            recyclerView.setLayoutParams(layoutParams);
        }
    }

    @Override
    public void showEnergyValue(LoginData loginData) {
        String energy = loginData.getEnergy();

        float total = Float.valueOf(energy);
        tvTotal.setText(energy);
        if (total >= 15) {
            int storage = (int) (total - Float.valueOf(15));
            tvStorage.setText(String.valueOf(storage));
            tvAvailable.setText("15");
            mWaveHelper = new WaveHelper(waveView, 1);
            waveView.setWaterLevelRatio(1);
            mWaveHelper.start();
        } else {
            float level = total / Float.valueOf(15);
            Log.i(TAG, "showEnergyValue: " + level);
            mWaveHelper = new WaveHelper(waveView, level);
            mWaveHelper.start();
            waveView.setWaterLevelRatio(level);
            tvAvailable.setText(String.valueOf((int) total));
            tvStorage.setText("0");
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onStart(SHARE_MEDIA share_media) {
        DLog.e(TAG, "share onstart");
    }

    @Override
    public void onResult(SHARE_MEDIA share_media) {
        DLog.e(TAG, "share onResult");

        MessageEvent messageEvent = new MessageEvent();
        messageEvent.isLogin = true;
        EventBus.getDefault().post(messageEvent);
    }

    @Override
    public void onError(SHARE_MEDIA share_media, Throwable throwable) {
        DLog.e(TAG, "share onError");

    }

    @Override
    public void onCancel(SHARE_MEDIA share_media) {
        DLog.e(TAG, "share onCancel");
//        MessageEvent messageEvent = new MessageEvent();
//        messageEvent.isLogin = true;
//        EventBus.getDefault().post(messageEvent);

    }

    class FriendBoostAdapter extends RecyclerView.Adapter {
        List<Object> mObjects = new ArrayList<>();

        FriendBoostAdapter() {
            mObjects.add(null);
        }

        public void setFriends(List<FriendHelp> friends) {
            mObjects.addAll(friends);
            notifyDataSetChanged();
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            if (i == 0) {
                return new TextHolder(new FrameLayout(viewGroup.getContext()));
            }
            return new FriendBoostHolder(getLayoutInflater().inflate(R.layout.recycler_item_friend_boost, viewGroup, false));
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int i) {
            if (i != 0 && holder instanceof FriendBoostHolder) {
                FriendBoostHolder friendBoostHolder = (FriendBoostHolder) holder;
                FriendHelp friend = (FriendHelp) mObjects.get(i);
                Glide.with(FriendBoostActivity.this).load(friend.getHeadImg()).into(friendBoostHolder.profileImage);
                String phone = friend.getPhone();
                friendBoostHolder.tvUserName.setText(phone);
                friendBoostHolder.tvEnergyValue.setText("能量值+" + friend.getAddNum());
            }
            if (holder instanceof TextHolder) {
                TextHolder textHolder = (TextHolder) holder;
                textHolder.tvEnergyCount.setText("已获得" + (mObjects.size() - 1) + "个能量值");
            }
        }

        @Override
        public int getItemCount() {
            return mObjects == null ? 1 : mObjects.size();
        }

        @Override
        public int getItemViewType(int position) {
            if (position == 0) {
                return 0;
            }
            return 1;
        }
    }

    class FriendBoostHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.profile_image)
        CircleImageView profileImage;
        @BindView(R.id.tv_user_name)
        TextView tvUserName;
        @BindView(R.id.tv_energy_value)
        TextView tvEnergyValue;

        public FriendBoostHolder(@NonNull View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    class TextHolder extends RecyclerView.ViewHolder {
        TextView tvEnergyCount;

        public TextHolder(@NonNull View itemView) {
            super(itemView);
            FrameLayout frameLayout = (FrameLayout) itemView;
            frameLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));

            tvEnergyCount = new TextView(itemView.getContext());
            frameLayout.addView(tvEnergyCount);
            tvEnergyCount.setTextColor(0xFF917317);
            tvEnergyCount.setText("已获得6个能量值");
            tvEnergyCount.setGravity(Gravity.CENTER);
            tvEnergyCount.setTextSize(15);
            ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) tvEnergyCount.getLayoutParams();
            layoutParams.topMargin = mDp15;
        }
    }


}
